package com.emagic.manage.modules.main.presenter;

import android.text.TextUtils;

import com.emagic.manage.data.entities.response.OutOffResponse;
import com.emagic.manage.data.exception.BizException;
import com.emagic.manage.modules.main.domain.GetOutOffUserCase;
import com.emagic.manage.modules.main.view.OutOffAppView;
import com.emagic.manage.mvp.presenters.Presenter;
import com.emagic.manage.mvp.views.InterfaceView;
import com.fernandocejas.frodo.annotation.RxLogSubscriber;
import com.xitaiinfo.library.injections.ActivityScope;

import javax.inject.Inject;

import rx.Subscriber;

/**
 * Created by xiatian on 2017/11/1.
 */
@ActivityScope
public class OutOffAppPresenter implements Presenter {

    private GetOutOffUserCase getOutOffUserCase;
    private OutOffAppView view;

    @Inject
    public OutOffAppPresenter(GetOutOffUserCase getOutOffUserCase) {
        this.getOutOffUserCase = getOutOffUserCase;
    }

    @Override
    public void onResume() {

    }

    @Override
    public void onPause() {

    }

    @Override
    public void onDestroy() {
        getOutOffUserCase.unSubscribe();
    }

    @Override
    public void attachView(InterfaceView v) {
        this.view = (OutOffAppView) v;
    }

    public void outOff(String userid, String sessionid) {
        view.showProgress();
        getOutOffUserCase.setUserid(userid);
        getOutOffUserCase.setSessionid(sessionid);
        getOutOffUserCase.execute(new OutOffSubscriber());

    }

    @RxLogSubscriber
    private class OutOffSubscriber extends Subscriber<OutOffResponse> {

        @Override
        public void onCompleted() {
            view.hideProgress();
        }

        @Override
        public void onError(Throwable e) {
            view.hideProgress();
            if (e instanceof BizException) {
                String code = ((BizException) e).code();
                if (code.equals("-2")) {
                    view.showError("您的账号在其他设备登录");
                } else if (code.equals("1")) {
                    view.showError("帐号未激活");
                } else if (code.equals("2")) {
                    view.showError("帐号已冻结");
                } else if (code.equals("5")) {
                    view.showError("密码错误");
                } else if (code.equals("6")) {
                    view.showError("帐号不存在");
                } else {
                    view.showError("服务端异常");
                }
            } else {
                view.showError(e.getMessage());
            }
        }

        @Override
        public void onNext(OutOffResponse outOffResponse) {
            if (outOffResponse != null && !TextUtils.isEmpty(outOffResponse.getResult())) {
                view.outOffSuccess();
            }

        }
    }
}
